import { ChangeDetectorRef, Component, Injector, OnInit } from '@angular/core';
import { ControlWidget, SFComponent, SFItemComponent } from '@delon/form';
import { format, getISOWeek } from 'date-fns';

@Component({
  selector: 'sl-from-to',
  templateUrl: './from-to.widget.html',
  styleUrls: ['./from-to.widget.less'],
  preserveWhitespaces: false,
})
export class EAFromToWidget extends ControlWidget implements OnInit {
  static readonly KEY = 'sl-from-to';
  /**
   * 组件类型
   */
  type: 'date' | 'number' = 'date';
  /**
   * 控件模式
   */
  mode: 'date' | 'week' | 'month' | 'year' = 'date';
  /**
   * 组件返回值
   */
  data: { start: any; end: any } | null = null;
  /**
   * 组件日期显示格式
   */
  displayFormat = 'yyyy-MM-dd';
  /**
   * 组件日期格式
   */
  format = 'yyyy-MM-dd';
  /**
   * 最小值
   */
  min: any;
  /**
   * 最大值
   */
  max: any;
  /**
   * 日期区间
   */
  date: any;

  constructor(cd: ChangeDetectorRef, injector: Injector, sfItemComp?: SFItemComponent, sfComp?: SFComponent) {
    super(cd, injector, sfItemComp, sfComp);
  }

  ngOnInit(): void {
    this.data = this.formProperty?.formData as { start: any; end: any };
    this.date = this.initData(this.data);
    this.type = this.ui?.type || 'date';
    this.mode = this.ui?.mode || 'date';
    this.displayFormat = this.ui?.displayFormat;
    this.format = this.ui?.format || 'yyyy-MM-dd';
  }

  initData(data: { start: any; end: any }): Date[] | null {
    return data ? [new Date(this.data?.start), new Date(this.data?.end)] : null;
  }

  onChange(result: Array<any>): void {
    // console.log('onChange: ', result);
    if (this.type === 'date') {
      if (JSON.stringify(result) !== '[]') {
        this.setValue({ start: format(result[0], this.format), end: format(result[1], this.format) });
      } else {
        this.setValue({ start: '', end: '' });
      }
    } else if (this.type === 'number') {
    } else {
      this.setValue(null);
    }
  }

  getWeek(result: Date[]): void {
    console.log('week: ', result.map(getISOWeek));
  }

  _change(value: string): void {
    this.setValue(value);
  }

  reset(value: string) {
    this.date = [];
  }
}
